import 'dart:ffi';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/rider/OrderListPage.dart';
import 'package:url_launcher/url_launcher.dart';

/**
 * 订单详情
 */
class OrderDetail extends StatefulWidget {
  var orid;
  OrderDetail({Key key, this.orid,}) : super(key: key);

  @override
  _OrderDetail createState() => _OrderDetail(orid);
}

class _OrderDetail extends State<OrderDetail> {
  var orid;           //订单ID
  var orderDetailInfo;//订单信息
  String riderId;     //骑手ID
  _OrderDetail(this.orid) {
    getDataSync();
  }
  // 加载订单详情
  getDataSync() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    riderId = prefs.getString("riderId");
    var x  = await HttpUtil().get("/waimai/mOder/getMOrderById?orId="+orid);
    if(x['code']==200){
      setState(() {
        orderDetailInfo = x['data'];
      });
    }
  }
// 显示订单中的商品
//   Container _showGoods(item){
//     // print(item['num']);
//     return Container(
//       height: 80,
//       child:Row(
//         mainAxisAlignment: MainAxisAlignment.spaceAround,
//         crossAxisAlignment: CrossAxisAlignment.center,
//         children: [
//           Checkbox(value: item['isSelect'], onChanged: (val){// 点击勾选
//             item['isSelect']=val;
//             setState(() {
//
//             });
//           }),
//           Image.asset("assets/phone2.jpg",width: 200,),
//           Expanded(
//             child: Column(
//               children: [
//                 Text(item['gname']),
//                 Text("红色;8+256GB"),
//                 Text("￥${item['gprice']}"),
//                 Container(
//                   child: Row(
//                     children: [
//                       GestureDetector(onTap: (){
//                         if(item['num']>1)
//                           item['num']--;
//                         setState(() {
//
//                         });
//                       },
//                           child:Container(
//                             width: 30,
//                             height: 20,
//                             decoration: BoxDecoration(
//                                 border: Border.all(
//                                   color: Colors.black12,
//                                   width: 1.0,
//                                 ),
//                                 borderRadius: BorderRadius.circular(3.0)
//                             ),
//                             child:Center(child: Text("-"),) ,
//                           )
//                       ),
//                       Text("${item['num']}"),
//                       GestureDetector(onTap: (){
//                         item['num']++;
//                         setState(() {
//
//                         });
//                       },
//                       child:Container(
//                         width: 30,
//                         height: 20,
//                         decoration: BoxDecoration(
//                             border: Border.all(
//                               color: Colors.black12,
//                               width: 1.0,
//                             ),
//                             borderRadius: BorderRadius.circular(3.0)
//                         ),
//                         child:Center(child:  Text("+"),),
//                       )),
//                     ],
//                   ),
//                 )// Positioned(child: Text("*1"),right: 10,),
//               ],
//             )
//           )
//         ],
//       ) ,
//     );
//   }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("订单详情"),
        centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          new Expanded(
            child: Container(
              padding:EdgeInsets.all(10),
              child: ListView(
                children: [
                  showOrderInfo(),
                  // Container(
                  //   decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
                  //   padding: EdgeInsets.all(10),
                  //   margin: EdgeInsets.only(top: 10),
                  //   child: Column(
                  //     children: [
                  //       Row(children: [
                  //         Icon(Icons.card_giftcard),
                  //         Text(orderDetailInfo['merchant']['mname'])
                  //       ]),
                  //       Container(
                  //         child: Column(
                  //           children: [
                  //             Row(
                  //               children: [
                  //                 CachedNetworkImage(imageUrl: Config.getInstance().getHost()+orderDetailInfo['morderDetailList'][0]['mgoods']['gimages'],width: 50,),
                  //                 Text(orderDetailInfo['morderDetailList'][0]['mgoods']['gname'])
                  //               ],
                  //             ),
                  //             Row(
                  //               mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  //               children: [
                  //                 Text(orderDetailInfo['morderDetailList'][0]['guiges']??""),
                  //                 Text("*"+orderDetailInfo['morderDetailList'][0]['odNum'].toString())
                  //               ],
                  //             )
                  //           ],
                  //         ),
                  //       ),
                  //     ],
                  //   ),
                  // ),
                  // 配送至
                  SizedBox(height: 20,),
                  Container(
                    decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
                    padding: EdgeInsets.all(10),
                    margin: EdgeInsets.only(top: 10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text("配送至",style: TextStyle(fontWeight: FontWeight.bold),),
                        SizedBox(height: 10,),
                        Text(orderDetailInfo['address']['addressDetail']),
                        // Text("株洲天元区黄河北路"),
                        Divider(),
                        Row(children: [Text(orderDetailInfo['address']['adName']),SizedBox(width: 10,),
                          GestureDetector(
                            child: Text(orderDetailInfo['address']['adPhone']),
                            onTap: () async{

                                await launch("tel:"+orderDetailInfo['address']['adPhone']);

                            },
                          ),],),
                        SizedBox(height: 10,),
                        Text("备注："+orderDetailInfo['orRemark']),
                        SizedBox(height: 10,),
                        Text("下单时间："+orderDetailInfo['orTime'],style: TextStyle(color: Colors.black12),)
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
          Row(
            children: <Widget>[
             Expanded(child:  Container(
               decoration: BoxDecoration(color: Colors.amber),
               padding: EdgeInsets.all(10),
               child: GestureDetector(
                 child: Center(child: Text(orderDetailInfo['orStatus']==1 ? "待商家出餐" : (orderDetailInfo['orStatus']==2 ? "已取货，开始配送" : (orderDetailInfo['orStatus']==3 ? "已送达" : (orderDetailInfo['orStatus']==4 ? "已送达，待评价" : "已评价"))))),
                 behavior: HitTestBehavior.opaque,
                 onTap: () async{
                   //订单状态订单状态（0：未支付  1：已支付,商家已接单,骑手已接单，正赶往商家  2：商家出餐完成  3：骑手已取货，配送中  4：已送达，待评价
                   //  5：已评价  6：退货换货申请中  7：退货换货完成  8：退款完成  9：取消订单）
                   int status = orderDetailInfo['orStatus'];
                   if(status == 2){
                     var x = await HttpUtil().get("/waimai/rider/updateOrderStatus?orId="+orderDetailInfo['id']+"&rid="+riderId+"&status=3");
                     if(x['code']==200){
                       Fluttertoast.showToast(
                         msg: "开始配送，小哥注意安全",
                       );
                       MyRoute.push(OrderListPage(showIndex: '1',));
                       // setState(() {});
                       // MyRoute.pop();
                     }else{
                       Fluttertoast.showToast(
                         msg: x['msg'],
                       );
                     }
                   }else if(status == 3){
                     var x = await HttpUtil().get("/waimai/rider/updateOrderStatus?orId="+orderDetailInfo['id']+"&rid="+riderId+"&status=4");
                     if(x['code']==200){
                       Fluttertoast.showToast(
                         msg: "已送达",
                       );
                       MyRoute.push(OrderListPage(showIndex: '2',));
                       // setState(() {});
                       // MyRoute.pop();
                     }else{
                       Fluttertoast.showToast(
                         msg: x['msg'],
                       );
                     }
                   }
                 },
               )
             ))
            ],
          )
        ]
      ),
    );
  }
  // 显示订单详情中的店铺和商品信息
  showOrderInfo() {
    var  x= List<Widget>();
    x.add( Row(children: [
      CachedNetworkImage(imageUrl: Config.getInstance().getHost()+orderDetailInfo['merchant']['picture'],width: 50,),
      Text(orderDetailInfo['merchant']['mname'])
    ])
    );
    for(var i=0;i<orderDetailInfo['morderDetailList'].length;i++){
      x.add(
          Container(
            child: Column(
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    CachedNetworkImage(imageUrl: Config.getInstance().getHost()+orderDetailInfo['morderDetailList'][i]['mgoods']['gimages'],width: 100,),
                    SizedBox(width: 10,),
                    Expanded(child:Text(orderDetailInfo['morderDetailList'][i]['mgoods']['gname'],style: TextStyle(fontWeight: FontWeight.bold),) )
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(orderDetailInfo['morderDetailList'][i]['guiges']??""),
                    Text("*"+orderDetailInfo['morderDetailList'][i]['odNum'].toString(),style: TextStyle(color: Colors.red),)
                  ],
                )
              ],
            ),
          )
      );
    }
    return Container(
      decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
      padding: EdgeInsets.all(10),
      margin: EdgeInsets.only(top: 10),
      child: Column(
        children: x,
      ),
    );


  }



}